package com.yunshang.shoppingmall.shopping.WeChat;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.yunshang.shoppingmall.common.HttpRequest;
import com.yunshang.shoppingmall.common.MessageConstants;
import com.yunshang.shoppingmall.common.Response;
import com.yunshang.shoppingmall.entity.*;
import com.yunshang.shoppingmall.service.PannerService;
import com.yunshang.shoppingmall.service.ShareImagesConfigService;
import com.yunshang.shoppingmall.service.WeChat.WeChatMuService;
import com.yunshang.shoppingmall.shopping.WeChat.common.WinChat;
import com.yunshang.shoppingmall.shopping.WeChat.common.WinxinUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class QrCodeController {

    @Autowired
    PannerService pannerService;

    @Autowired
    ShareImagesConfigService shareImagesConfigService;

    @Autowired
    WeChatMuService weChatMuService;

    @ResponseBody
    @RequestMapping("/WeChatQrcode")
    public Response WeChatQrcode(HttpServletRequest request, HttpServletResponse response) {
        HttpSession wxSession = request.getSession();
        UserNo userNo1 = (UserNo) wxSession.getAttribute("userNo");
        String uid = "";
        if (userNo1 != null) {
            uid = "" + userNo1.getId();
        } else {
            uid = "" + 62240;
        }
//        String access_token = WinxinUtil.getToken(WinChat.appid, WinChat.appsecret);
//        if (access_token != "") {
//            System.out.println(access_token);
//            String url = WinxinUtil.getTicket(access_token, uid);

        String url = WinChat.severUrl + "/wap/Share?lx=1&uid=" + uid;

        //生成二维码

        //logo图片
        int pannerActiveSign = 2;
        List<Panner> pannersList = pannerService.selectPanners(pannerActiveSign);
        String logoImgURL = pannersList.get(0).getPannerUrl();

        System.out.println("logo图片路径：" + logoImgURL);

        //二维码背景图图片
        pannerActiveSign = 300;
        List<Panner> pannersList1 = pannerService.selectPanners(pannerActiveSign);
        String imgURL = pannersList1.get(0).getPannerUrl();
        System.out.println("背景图路径：" + imgURL);

        //合成图片的参数
        ShareImagesConfig shareImagesConfig = shareImagesConfigService.selectByPrimaryKey(2);
        System.out.println("X:" + shareImagesConfig.getEwmImgX().toString());
        System.out.println("Y:" + shareImagesConfig.getEwmImgY().toString());

        String urlEwm = WinxinUtil.getEWMU(url, logoImgURL, imgURL, shareImagesConfig.getEwmImgX().toString(), shareImagesConfig.getEwmImgY().toString());
        if (urlEwm != null) {
            return new Response(MessageConstants.MSG_SUCCESS, urlEwm, 1, "");
        }

        System.out.println(url);
//        }
//        pesponse = new Response(MessageConstants.MSG_SYS_ERROR, null, 0, "生成二维码失败");
//
//        System.out.println(pesponse.toString());

        return new Response(MessageConstants.MSG_SYS_ERROR, null, 0, "生成二维码失败");
    }



    @ResponseBody
    @RequestMapping("/WeChat/UpdateMu")
    public Response UpdateMu(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String access_token = WinxinUtil.getToken(WinChat.appid, WinChat.appsecret);
        if (access_token != "") {

            List<WeChatMenu> muList=weChatMuService.selectMenuList();
            if(muList!=null) {
                String jsonMu = JSON.toJSONString(muList);
                try {
                    String url = WinChat.MENU_CREATE_URL;
                    url = url.replace("ACCESS_TOKEN",access_token);
                    System.out.println("url:"+url);

                    jsonMu="{\"button\":"+jsonMu+"}";

                    jsonMu = jsonMu.replace("SeverUrl",WinChat.severUrl);

                    System.out.println("Json:"+jsonMu);

                    String html= HttpRequest.sendPost(url,jsonMu);

                    if(html.contains("{\"errcode\":0,\"errmsg\":\"ok\"}"))
                    {
                        return new Response(MessageConstants.MSG_SUCCESS, null, 0, "更新菜单成功");
                    }
                    else
                    {
                        return new Response(MessageConstants.MSG_SYS_ERROR, html, 0, "更新菜单失败");
                    }
                    //System.out.println("返回消息:"+html);
                }
                catch (Exception ex)
                {
                    System.out.println("错误消息："+ex.getMessage());
                }
            }

        }

        return new Response(MessageConstants.MSG_SYS_ERROR, null, 0, "更新菜单失败");
    }

    @ResponseBody
    @RequestMapping("/WeChat/SendMessage")
    public Response SendMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String phone = request.getParameter("phone");
        String wOpenid = request.getParameter("openid");

        //发送公众号消息
        String txtJson1="\"first\": {\"value\":\"欢迎您加入荟品汇享（新零售微店）\",\"color\":\"#173177\"}," +
                "\"keyword1\":{\"value\":\""+phone+"\",\"color\":\"#173177\"}," +
                "\"keyword2\":{\"value\":\"XLS"+phone+"\",\"color\":\"#173177\"}," +
                "\"keyword3\":{\"value\":\""+sdf.format(new Date())+"\",\"color\":\"#173177\"}," +
                "\"remark\":{\"value\":\"会员密码："+phone+"\",\"color\":\"#173177\"}";
        String template_id="UE4QSWZX9yxHBSTxtemMoorBmYsE_gme8NU8K9JusMc";
        String url=WinChat.severUrl;
        if(WinxinUtil.sendMessage(txtJson1,wOpenid,template_id,url))
        {
            return new Response(MessageConstants.MSG_SUCCESS, wOpenid, 0, "发送成功");
        }
        return new Response(MessageConstants.MSG_SYS_ERROR, null, 0, "发送失败");
    }

    @ResponseBody
    @RequestMapping("/WeChat/SmsMessage")
    public Response SmsMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String phone = request.getParameter("phone");
        //发送短信消息
        String templateCode="SMS_165117417";
        String txtJson="{\"product\":\"Dysmsapi\", \"userno\":\"XLS" + phone+"\", \"pwd\":\"" + phone+"\"}";
        try {
            SendSmsResponse response1 = SmsDemo.sendSms(phone, templateCode,txtJson);
            if ("OK".equalsIgnoreCase(response1.getCode())) {
                //json = "{\"stat\":\"100\",\"message\":\"发送成功！\"}";
                return new Response(MessageConstants.MSG_SUCCESS, phone, 0, "发送成功");
            }
            else
            {
                return new Response(MessageConstants.MSG_SYS_ERROR, response1.getMessage(), 0, "发送失败");
            }
        }
        catch (Exception ex)
        {
            return new Response(MessageConstants.MSG_SYS_ERROR, ex.getMessage(), 0, "发送失败");
        }
    }
}
